package exercises.newcoder.util;

import java.io.Serializable;
import java.util.function.Consumer;

/**
 * @author or2
 * @Description 牛客网 - 链表结构
 * @create 2021年09月13日 时间: 13:06
 */
public class ListNode implements Serializable, Cloneable {
    public int val;
    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    /**
     * 仅 leetcode 可用
     * @param val 新结点的值
     * @param next 新结点的下一个结点
     */
    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    /**
     * 将牛客王字符串输入->链表
     *
     * @param str 牛客网 输入字符串
     * @return 链表第一个结点
     */
    public static ListNode getByIn(String str) {
        str = str.substring(1, str.length() - 1);
        String[] split = str.split(",");
        ListNode pre = new ListNode(Integer.parseInt(split[0]));
        ListNode head = pre;
        for (int i = 1, splitLength = split.length; i < splitLength; i++) {
            ListNode p = new ListNode(Integer.parseInt(split[i]));
            pre.next = p;
            pre = p;
        }

        return head;
    }

    public void foreach(Consumer<Integer> consumer) {
        ListNode p = this;
        while (p != null) {
            consumer.accept(p.val);
            p = p.next;
        }
    }

    @Override
    public ListNode clone() {
        try {
            ListNode clone = (ListNode) super.clone();
//——————————— 浅拷贝测试 —————————————————————————————————————————————————
            if (this.next != null) {
                clone.next = this.next.clone();
            }
//——————————————————————————————————————————————————————————————————————
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    @Override
    public String toString() {
        StringBuilder toString = new StringBuilder();
        ListNode p = this;
        while (p != null) {
            toString.append(p.val).append("-> ");
            p = p.next;
        }

        int length = toString.length();
        toString.delete(length - 3, length);
        return toString.toString();
    }

    /**
     * 浅克隆 - 默认方式
     *
     * @return 浅克隆的当前对象
     */
    public ListNode badClone() {
        try {
            return (ListNode) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
